<template>
  <div class="dashboard-page">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <div>
        <h1 class="text-2xl font-bold text-slate-800 ">仪表板</h1>
      </div>
    </div>
    
    <!-- 数据可视化图表 -->
    <el-row :gutter="20" class="mb-6">
      <el-col :xs="24" :lg="12" class="mb-6">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-medium">新闻发布趋势</h3>
              <el-select v-model="newsTrendPeriod" size="small" style="width: 100px">
                <el-option label="按天" value="day" />
                <el-option label="按周" value="week" />
                <el-option label="按月" value="month" />
              </el-select>
            </div>
          </template>
          <div class="chart-container">
            <ClientOnly>
              <v-chart v-if="VChart" :option="newsTrendOption" :loading="chartLoading" />
              <div v-else class="flex items-center justify-center h-full text-gray-500">
                图表加载中...
              </div>
            </ClientOnly>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="12" class="mb-6">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-medium">信源分布</h3>
              <el-button text @click="refreshSourceData">刷新</el-button>
            </div>
          </template>
          <div class="chart-container">
            <ClientOnly>
              <v-chart v-if="VChart" :option="sourceDistributionOption" :loading="chartLoading" />
              <div v-else class="flex items-center justify-center h-full text-gray-500">
                图表加载中...
              </div>
            </ClientOnly>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="mb-6">
      <el-col :xs="24" :lg="12" class="mb-6">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-medium">分类统计</h3>
              <el-button text @click="refreshCategoryData">刷新</el-button>
            </div>
          </template>
          <div class="chart-container">
            <ClientOnly>
              <v-chart v-if="VChart" :option="categoryStatsOption" :loading="chartLoading" />
              <div v-else class="flex items-center justify-center h-full text-gray-500">
                图表加载中...
              </div>
            </ClientOnly>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="12" class="mb-6">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-medium">任务执行状态</h3>
              <el-button text @click="refreshTaskData">刷新</el-button>
            </div>
          </template>
          <div class="chart-container">
            <ClientOnly>
              <v-chart v-if="VChart" :option="taskStatusOption" :loading="chartLoading" />
              <div v-else class="flex items-center justify-center h-full text-gray-500">
                图表加载中...
              </div>
            </ClientOnly>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 快速访问区域 -->
    <div class="mb-6">
      <h2 class="text-xl font-semibold mb-4 text-slate-700 ">快速访问</h2>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="(item, index) in quickAccess" :key="index" class="mb-4">
          <el-card 
            class="quick-access-card cursor-pointer transition-all duration-300 transform hover:-translate-y-1 hover:shadow-md" 
            shadow="hover"
            @click="navigateTo(item.path)"
          >
            <div class="flex items-center">
              <div class="quick-access-icon" :class="item.iconClass">
                <el-icon><i :class="item.icon"></i></el-icon>
              </div>
              <div class="ml-3">
                <div class="quick-access-title">{{ item.title }}</div>
                <div class="quick-access-desc">{{ item.description }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 最近新闻和任务 -->
    <el-row :gutter="20">
      <el-col :xs="24" :lg="12" class="mb-6">
        <el-card class="h-full" shadow="never">
          <template #header>
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-medium">最近新闻</h3>
              <el-button text @click="navigateTo('/admin/news/list')">查看全部</el-button>
            </div>
          </template>
          <el-table :data="recentNews" style="width: 100%" :show-header="false">
            <el-table-column>
              <template #default="scope">
                <div class="flex items-center py-1">
                  <div class="flex-1 truncate">
                    <div class="font-medium text-slate-700  truncate">{{ scope.row.title }}</div>
                    <div class="text-xs text-slate-500  mt-1 flex items-center">
                      <span>{{ scope.row.source }}</span>
                      <span class="mx-1">•</span>
                      <span>{{ scope.row.category }}</span>
                      <span class="mx-1">•</span>
                      <span>{{ scope.row.time }}</span>
                    </div>
                  </div>
                  <el-button 
                    size="small" 
                    text 
                    @click="navigateTo(`/admin/news/edit/${scope.row.id}`)"
                  >
                    编辑
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="12" class="mb-6">
        <el-card class="h-full" shadow="never">
          <template #header>
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-medium">最近任务</h3>
              <el-button text @click="navigateTo('/admin/task/list')">查看全部</el-button>
            </div>
          </template>
          <el-table :data="recentTasks" style="width: 100%" :show-header="false">
            <el-table-column>
              <template #default="scope">
                <div class="flex items-center py-1">
                  <div class="task-status" :class="getTaskStatusClass(scope.row.status)"></div>
                  <div class="flex-1 ml-3">
                    <div class="font-medium text-slate-700 ">{{ scope.row.name }}</div>
                    <div class="text-xs text-slate-500  mt-1">
                      {{ scope.row.time }} • {{ scope.row.source }}
                    </div>
                  </div>
                  <el-tag size="small" :type="getTaskTagType(scope.row.status)">
                    {{ scope.row.status }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { dashboardAPI } from '~/services/api'
// 客户端渲染 ECharts 组件
const VChart = ref(null)

// 异步加载 ECharts
const loadECharts = async () => {
  if (process.client) {
    try {
      const echarts = await import('vue-echarts')
      const core = await import('echarts/core')
      const renderers = await import('echarts/renderers')
      const charts = await import('echarts/charts')
      const components = await import('echarts/components')
      
      VChart.value = echarts.default
      
      // 注册 ECharts 组件
      core.use([
        renderers.CanvasRenderer,
        charts.LineChart,
        charts.PieChart,
        charts.BarChart,
        charts.GaugeChart,
        components.GridComponent,
        components.TooltipComponent,
        components.LegendComponent,
        components.TitleComponent
      ])
    } catch (error) {
      console.error('ECharts 加载失败:', error)
    }
  }
}

// 设置使用管理布局
definePageMeta({
  layout: 'admin'
})

const router = useRouter()



// 图表相关
const chartLoading = ref(false)
const newsTrendPeriod = ref('day')

// 新闻趋势数据
const newsTrendData = ref([])

// 信源分布数据
const sourceDistributionData = ref([])

// 分类统计数据
const categoryStatsData = ref([])

// 任务状态数据（暂时保持模拟数据，因为后端没有实现）
const taskStatusData = ref({
  success: 75,
  running: 15,
  failed: 10
})

  // 新闻趋势图配置
const newsTrendOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  grid: {
    left: '8%',
    right: '8%',
    top: '8%',
    bottom: '12%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: newsTrendData.value.map(item => item.date),
    axisLine: {
      lineStyle: {
        color: '#e2e8f0'
      }
    },
    axisLabel: {
      color: '#64748b'
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      lineStyle: {
        color: '#e2e8f0'
      }
    },
    axisLabel: {
      color: '#64748b'
    },
    splitLine: {
      lineStyle: {
        color: '#f1f5f9'
      }
    }
  },
  series: [
    {
      name: '新闻数量',
      type: 'line',
      smooth: true,
      data: newsTrendData.value.map(item => item.count),
      itemStyle: {
        color: '#6366f1'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(99, 102, 241, 0.3)' },
            { offset: 1, color: 'rgba(99, 102, 241, 0.1)' }
          ]
        }
      }
    }
  ]
}))

// 信源分布图配置
const sourceDistributionOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    textStyle: {
      color: '#64748b'
    }
  },
  series: [
    {
      name: '信源分布',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['60%', '50%'],
      data: sourceDistributionData.value,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        show: false
      },
      labelLine: {
        show: false
      }
    }
  ]
}))

  // 分类统计图配置
const categoryStatsOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '8%',
    right: '8%',
    top: '8%',
    bottom: '20%', // 增加底部空间，为旋转的标签留出位置
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: categoryStatsData.value.map(item => item.name),
    // 添加调试信息
    name: '分类',
    nameLocation: 'middle',
    nameGap: 30,
    axisLine: {
      lineStyle: {
        color: '#e2e8f0'
      }
    },
    axisLabel: {
      color: '#64748b',
      rotate: 45, // 旋转标签，避免重叠
      fontSize: 9, // 进一步减小字体大小
      interval: 0, // 强制显示所有标签
      textStyle: {
        overflow: 'break' // 文字过长时换行
      },
      formatter: function(value) {
        // 如果文字太长，进行截断处理
        if (value.length > 4) {
          return value.substring(0, 4) + '...'
        }
        return value
      }
    },
    axisTick: {
      alignWithLabel: true
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      lineStyle: {
        color: '#e2e8f0'
      }
    },
    axisLabel: {
      color: '#64748b'
    },
    splitLine: {
      lineStyle: {
        color: '#f1f5f9'
      }
    }
  },
  series: [
    {
      name: '新闻数量',
      type: 'bar',
      data: categoryStatsData.value.map(item => item.value),
      barWidth: '60%', // 设置柱子宽度，确保有足够空间
      itemStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: '#10b981' },
            { offset: 1, color: '#059669' }
          ]
        }
      }
    }
  ]
}))

// 任务状态图配置
const taskStatusOption = computed(() => ({
  series: [
    {
      name: '任务状态',
      type: 'gauge',
      progress: {
        show: true,
        width: 12
      },
      axisLine: {
        lineStyle: {
          width: 12
        }
      },
      axisTick: {
        show: false
      },
      splitLine: {
        length: 8,
        lineStyle: {
          width: 1,
          color: '#999'
        }
      },
      axisLabel: {
        distance: 15,
        color: '#999',
        fontSize: 10
      },
      anchor: {
        show: true,
        showAbove: true,
        size: 18,
        itemStyle: {
          borderWidth: 6
        }
      },
      title: {
        show: false
      },
      detail: {
        valueAnimation: true,
        fontSize: 20,
        offsetCenter: [0, '60%'],
        formatter: '{value}%',
        color: '#6366f1'
      },
      data: [
        {
          value: taskStatusData.value.success,
          name: '成功率'
        }
      ]
    }
  ]
}))

// 快速访问项
const quickAccess = ref([
  {
    title: '新闻管理',
    description: '查看和编辑新闻内容',
    icon: 'el-icon-document',
    iconClass: 'bg-indigo-100  text-indigo-600 ',
    path: '/admin/news/list'
  },
  {
    title: '信源配置',
    description: '管理新闻来源',
    icon: 'el-icon-connection',
    iconClass: 'bg-blue-100  text-blue-600 ',
    path: '/admin/source/list'
  },
  {
    title: '分类管理',
    description: '管理新闻分类',
    icon: 'el-icon-collection-tag',
    iconClass: 'bg-green-100  text-green-600 ',
    path: '/admin/category/list'
  },
  {
    title: '区域管理',
    description: '管理地域分类',
    icon: 'el-icon-location',
    iconClass: 'bg-yellow-100  text-yellow-600 ',
    path: '/admin/region/list'
  },
  {
    title: '任务管理',
    description: '管理抓取任务',
    icon: 'el-icon-alarm-clock',
    iconClass: 'bg-purple-100  text-purple-600 ',
    path: '/admin/task/list'
  },
  {
    title: '系统设置',
    description: '配置系统参数',
    icon: 'el-icon-setting',
    iconClass: 'bg-gray-100  text-gray-600 ',
    path: '/admin/system/settings'
  },
  {
    title: '用户管理',
    description: '管理系统用户',
    icon: 'el-icon-user',
    iconClass: 'bg-red-100  text-red-600 ',
    path: '/admin/user/list'
  },
  {
    title: '数据统计',
    description: '查看数据分析',
    icon: 'el-icon-data-analysis',
    iconClass: 'bg-cyan-100  text-cyan-600 ',
    path: '/admin/stats/overview'
  }
])

// 最近新闻
const recentNews = ref([
  { id: 1, title: '中国经济稳步增长，多项指标向好', source: '新华网', category: '经济', time: '10分钟前' },
  { id: 2, title: '科技创新引领产业升级，人工智能应用广泛', source: '人民日报', category: '科技', time: '30分钟前' },
  { id: 3, title: '国际合作论坛召开，共商发展大计', source: '中国日报', category: '政治', time: '1小时前' },
  { id: 4, title: '环保政策出台，绿色发展成为共识', source: '光明网', category: '环境', time: '2小时前' },
  { id: 5, title: '文化交流活动举行，促进民心相通', source: '央视网', category: '文化', time: '3小时前' }
])

// 最近任务
const recentTasks = ref([
  { id: 1, name: '新华网首页抓取', source: '新华网', status: '成功', time: '10分钟前' },
  { id: 2, name: '人民日报要闻抓取', source: '人民日报', status: '进行中', time: '30分钟前' },
  { id: 3, name: '中国日报国际新闻抓取', source: '中国日报', status: '失败', time: '1小时前' },
  { id: 4, name: '光明网评论抓取', source: '光明网', status: '等待中', time: '2小时前' },
  { id: 5, name: '央视网视频新闻抓取', source: '央视网', status: '成功', time: '3小时前' }
])

// 页面导航
const navigateTo = (path) => {
  router.push(path)
}

// 获取任务状态样式
const getTaskStatusClass = (status) => {
  switch (status) {
    case '成功':
      return 'bg-green-500'
    case '失败':
      return 'bg-red-500'
    case '进行中':
      return 'bg-blue-500'
    case '等待中':
      return 'bg-yellow-500'
    default:
      return 'bg-gray-500'
  }
}

// 获取任务标签类型
const getTaskTagType = (status) => {
  switch (status) {
    case '成功':
      return 'success'
    case '失败':
      return 'danger'
    case '进行中':
      return 'primary'
    case '等待中':
      return 'warning'
    default:
      return 'info'
  }
}

// 刷新图表数据
const refreshSourceData = async () => {
  chartLoading.value = true
  try {
    const response = await dashboardAPI.getSourceDistribution()
    if (response.code === 200) {
      sourceDistributionData.value = response.data.data.pieData
    }
  } catch (error) {
    console.error('获取信源分布数据失败:', error)
  } finally {
    chartLoading.value = false
  }
}

const refreshCategoryData = async () => {
  chartLoading.value = true
  try {
    const response = await dashboardAPI.getCategoryStats()
    if (response.code === 200) {
      categoryStatsData.value = response.data.data.barData
    }
  } catch (error) {
    console.error('获取分类统计数据失败:', error)
  } finally {
    chartLoading.value = false
  }
}

const refreshTaskData = async () => {
  chartLoading.value = true
  chartLoading.value = false
}

// 监听新闻趋势周期变化
watch(newsTrendPeriod, async (newPeriod) => {
  // 根据周期更新数据
  console.log('更新新闻趋势数据，周期:', newPeriod)
  await loadNewsTrendData(newPeriod)
})

// 加载新闻趋势数据
const loadNewsTrendData = async (period = 'day') => {
  chartLoading.value = true
  try {
    const response = await dashboardAPI.getNewsTrend(period)
    if (response.code === 200) {
      // 将后端数据转换为前端需要的格式
      const dates = response.data.data.dates
      const counts = response.data.data.counts
      newsTrendData.value = dates.map((date, index) => ({
        date: date,
        count: counts[index]
      }))
    }
  } catch (error) {
    console.error('获取新闻趋势数据失败:', error)
  } finally {
    chartLoading.value = false
  }
}

// 加载信源分布数据
const loadSourceDistributionData = async () => {
  chartLoading.value = true
  try {
    const response = await dashboardAPI.getSourceDistribution()
    if (response.code === 200) {
      sourceDistributionData.value = response.data.data.pieData
    }
  } catch (error) {
    console.error('获取信源分布数据失败:', error)
  } finally {
    chartLoading.value = false
  }
}

// 加载分类统计数据
const loadCategoryStatsData = async () => {
  chartLoading.value = true
  try {
    const response = await dashboardAPI.getCategoryStats()
    console.log('分类统计API响应:', response)
    if (response.code === 200) {
      console.log('分类统计原始数据:', response.data.data)
      categoryStatsData.value = response.data.data.barData
      console.log('设置后的分类统计数据:', categoryStatsData.value)
    }
  } catch (error) {
    console.error('获取分类统计数据失败:', error)
  } finally {
    chartLoading.value = false
  }
}

// 初始化数据
onMounted(async () => {
  // 加载 ECharts
  loadECharts()
  
  // 加载所有图表数据
  await Promise.all([
    loadNewsTrendData('day'),
    loadSourceDistributionData(),
    loadCategoryStatsData()
  ])
  
  console.log('仪表盘页面加载完成')
})
</script>

<style scoped>


.chart-card {
  transition: all 0.3s ease;
}

.chart-container {
  height: 200px;
  width: 100%;
}

.quick-access-card {
  transition: all 0.3s ease;
}

.quick-access-icon {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  transition: all 0.3s ease;
}

.quick-access-title {
  font-size: 15px;
  font-weight: 500;
  color: var(--light-text);
  line-height: 1.2;
}

.quick-access-desc {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 2px;
}


.task-status {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

/* 表格样式优化 */
:deep(.el-table) {
  --el-table-border-color: transparent !important;
  --el-table-header-bg-color: transparent !important;
  --el-table-row-hover-bg-color: rgba(0, 0, 0, 0.02) !important;
}


:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-card__header) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}


/* ECharts 暗色模式适配 */
</style>